import { createSlice } from '@reduxjs/toolkit'
import { Dispatch } from 'redux'

const slice = createSlice({
  //创建一个全局状态
  name: 'money', //唯一的一个值
  initialState: {
    //初始值
    money: 1000,
  },
  reducers: {
    //改变全局状态的方法，相当于redux中的action
    recharge(preState:MoneyState['money'], action) {
      //充值
      preState.money += action.payload
    },
    buy(preState:MoneyState['money'], action) {
      //消费
      preState.money -= action.payload
    },
  },
})

const sleep = (ms:number): Promise<void> =>{
  return new Promise((resolve)=>{
    setTimeout(()=>{
      resolve() //成功时，调用resolve
    },ms)
  })
}
//const sleep = ms => new Promise(resolve => setTimeout(resolve,ms))

//导出一个异步执行的函数，返回值是一个函数，参数的参数是dispatch，实质 = useDispatch()
//导出去的一部函数的使用方法和slice.actions中的方法一致
export function weixinRecharge(count:number){
  return async(dispatch:Dispatch)=>{
    await sleep(3000)//延时3s
    dispatch(recharge(count))
  }
}

//导出改变全局状态的函数
export const { recharge, buy } = slice.actions
export interface MoneyNumber {
  money: number
}
export interface MoneyState {
  money: MoneyNumber
}
//默认导出整个reducer
export default slice.reducer
